<?php

/**
 * descript:
 * User: blue
 * Date: 2018/9/14 15:21
 */

namespace app\api\controller\v1;

use app\api\validate\GroupValid;
use app\library\base\BaseController;
use rabbit\base\Regular;
use think\Exception;
use think\facade\Request;
use app\api\model\Group as GroupModel;

class Group extends BaseController
{
    //权限控制
    protected $beforeActionList=[
            'checkAuth'=>['only'=>'addc,updatec,delc,assign_rule,group_add_user,group_del_user']
    ];

    protected $validname="\\app\\api\\validate\\GroupValid";
    protected $modelName="\\app\\api\\model\\Group";

    /*设置组的权限*/
    public function assign_rule(){
        //接收授权规则的id
        $data=Request::post();
        Regular::positive($data['group_id']);
        Regular::checkIds($data['rule_ids']);
        // 更新group 表中的rule字段
        $group=groupModel::get($data['group_id']);
        $group->rules=$data['rule_ids'];
        $res=$group->save();
        return successStatus('ok',$res);
    }

    /*组增加成员
    参数为1 或1,2,3
     */
    public function group_add_user(){
        //接收成员的id号
        $user_ids=Request::post('user_ids');
        $id=Request::post('group_id');
        Regular::checkIds($user_ids);
        (new GroupValid())->goCheck(['id'=>$id],'delete');
        //中间表中添加组成员id
        $group=GroupModel::get($id);
        $user_ids_arr=explode(',',$user_ids);
        if(empty($user_ids_arr)) throw new Exception('user_ids 转换数组失败');
        //添加前需要判断用户是否存在,且不能重复添加

        $res=$group->user()->saveAll($user_ids_arr);
        return successStatus('ok',$res);
    }

    /*组解除成员授权
     */
    public function group_del_user(){
        //接收成员的id号
        $group_id=Request::post('group_id');
        $user_id=Request::post('user_id');
        Regular::positive($group_id);
        Regular::positive($user_id);
        //中间表删除相关成员id
        $group=GroupModel::get($group_id);
        $res=$group->user()->detach($user_id);
        return successStatus('ok',$res);
    }

}